package com.bys.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity // 开启 spring security
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }

    /**
     * 认证管理器
     */
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 不应创建任何与session相关的状态
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.csrf().disable()
                .cors()   //开启跨域
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST,"/system/sysUser/login").permitAll()
                .antMatchers(HttpMethod.POST,"/system/sysUser/signup").permitAll()
                .antMatchers(HttpMethod.GET,"/system/sysUser/sendCode/**").permitAll()
                .antMatchers(HttpMethod.POST,"/system/sysUser/code/login").permitAll()
                .anyRequest().authenticated();
        //TokenAuthenticationFilter放到UsernamePasswordAuthenticationFilter的前面，这样做就是为了除了登录的时候去查询数据库外，其他时候都用token进行认证。
        http.addFilterBefore(new TokenAuthFilter(stringRedisTemplate), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new TokenLoginFilter(authenticationManager(),stringRedisTemplate), TokenAuthFilter.class);
        http.exceptionHandling().authenticationEntryPoint(new AuthLoginHandler()).accessDeniedHandler(new AccessHandler());
    }

    /**
     * 配置 加密和 userService
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/favicon.ico","/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/doc.html");
    }
}
